<template>
  <div class="table-management-container">
    <el-card class="box-card">
      <template #header>
        <div class="card-header">
          <span class="title">餐桌管理</span>
          <el-button type="primary" @click="handleAdd">添加餐桌</el-button>
        </div>
      </template>

      <!-- 搜索和过滤区域 -->
      <div class="search-area">
        <el-row :gutter="20">
          <el-col :span="5">
            <el-input
              v-model="searchQuery"
              placeholder="请输入餐桌名称搜索"
              clearable
            >
              <template #prefix>
                <el-icon><Search /></el-icon>
              </template>
            </el-input>
          </el-col>
          <el-col :span="5">
            <el-select v-model="filterType" placeholder="餐桌类型" clearable>
              <el-option label="普通" value="普通" />
              <el-option label="包厢" value="包厢" />
            </el-select>
          </el-col>
          <el-col :span="5">
            <el-select v-model="filterStatus" placeholder="餐桌状态" clearable>
              <el-option
                v-for="status in statusOptions"
                :key="status.value"
                :label="status.label"
                :value="status.value"
              ></el-option>
            </el-select>
          </el-col>
          <el-col :span="5">
            <el-input-number
              v-model="filterSeat"
              :min="1"
              :max="20"
              placeholder="座位数"
              clearable
              style="width: 100%"
            />
          </el-col>
          <el-col :span="4" style="text-align: right;">
            <el-button @click="resetSearch">重置</el-button>
          </el-col>
        </el-row>
      </div>

      <!-- 表格区域 -->
      <div class="table-container">
        <table class="table-list">
          <thead>
            <tr>
              <th>编号</th>
              <th>餐桌名称</th>
              <th>座位数</th>
              <th>餐桌类型</th>
              <th>状态</th>
              <th>操作</th>
            </tr>
          </thead>
          <tbody>
            <tr v-for="item in filteredTables" :key="item.boardId">
              <td>{{ item.boardId }}</td>
              <td>{{ item.boardName }}</td>
              <td>{{ item.seat }}</td>
              <td>
                <el-tag :type="item.boardType === '包厢' ? 'success' : 'info'">
                  {{ item.boardType }}
                </el-tag>
              </td>
              <td>
                <el-tag :type="getStatusType(item.boardStatus)">
                  {{ getStatusText(item.boardStatus) }}
                </el-tag>
              </td>
              <td class="actions-column">
                <div class="action-buttons">
                  <el-button-group>
                    <el-button
                      size="small"
                      type="primary"
                      @click="handleEdit(item)"
                    >
                      编辑
                    </el-button>
                    <el-button
                      size="small"
                      type="danger"
                      @click="handleDelete(item)"
                    >
                      删除
                    </el-button>
                  </el-button-group>
                </div>
              </td>
            </tr>
          </tbody>
        </table>
      </div>
    </el-card>

    <!-- 添加/编辑对话框 -->
    <el-dialog
      v-model="dialogVisible"
      :title="dialogType === 'add' ? '添加餐桌' : '编辑餐桌'"
      width="50%"
      @close="resetForm"
    >
      <el-form :model="form" :rules="rules" ref="formRef" label-width="100px">
        <el-form-item label="餐桌名称" prop="boardName">
          <el-input v-model="form.boardName" placeholder="请输入餐桌名称" />
        </el-form-item>
        <el-form-item label="座位数" prop="seat">
          <el-input-number 
            v-model="form.seat" 
            :min="1" 
            controls-position="right"
          ></el-input-number>
        </el-form-item>
        <el-form-item label="餐桌类型" prop="boardType">
          <el-select v-model="form.boardType" placeholder="请选择餐桌类型">
            <el-option
              v-for="option in typeOptions"
              :key="option.value"
              :label="option.label"
              :value="option.value"
            />
          </el-select>
        </el-form-item>
        <el-form-item label="餐桌状态" prop="boardStatus" v-if="dialogType === 'edit'">
          <el-select v-model="form.boardStatus" placeholder="请选择餐桌状态">
            <el-option
              v-for="option in statusOptions"
              :key="option.value"
              :label="option.label"
              :value="option.value"
            />
          </el-select>
        </el-form-item>
      </el-form>
      <template #footer>
        <span class="dialog-footer">
          <el-button @click="dialogVisible = false">取消</el-button>
          <el-button type="primary" @click="handleSubmit">确定</el-button>
        </span>
      </template>
    </el-dialog>
  </div>
</template>

<script setup lang="ts">
import { ref, onMounted, computed, watch } from 'vue'
import { Search } from '@element-plus/icons-vue'
import { ElMessage, ElMessageBox } from 'element-plus'
import type { FormInstance } from 'element-plus'
import { boardApi } from '../api/console'

// 接口类型定义
interface Table {
  boardId: number
  boardName: string
  seat: number
  boardStatus: string
  boardType: string
  regionId: number
}

// 状态定义
const loading = ref(false)
const dialogVisible = ref(false)
const dialogType = ref<'add' | 'edit'>('add')
const searchQuery = ref('')
const filterType = ref<string>('')
const filterStatus = ref<string>('')
const filterSeat = ref<number | null>(null)
const tables = ref<Table[]>([])
const formRef = ref<FormInstance>()

// 餐桌状态选项
const statusOptions = [
  { value: 'UNINHABITED', label: '空闲' },
  { value: 'BOOKING', label: '已预订' },
  { value: 'REPAST', label: '就餐中' },
  { value: 'DISABLE', label: '停用' }
]

// 餐桌类型选项
const typeOptions = [
  { value: '普通', label: '普通' },
  { value: '包厢', label: '包厢' }
]

// 表单数据
const form = ref<Table>({
  boardId: 0,
  boardName: '',
  seat: 4,
  boardType: '普通',
  boardStatus: 'UNINHABITED',
  regionId: 9 // 默认区域ID
})

// 表单验证规则
const rules = {
  boardName: [
    { required: true, message: '请输入餐桌名称', trigger: 'blur' },
    { min: 1, max: 50, message: '长度在 1 到 50 个字符', trigger: 'blur' }
  ],
  seat: [
    { required: true, message: '请选择座位数', trigger: 'change' }
  ],
  boardType: [
    { required: true, message: '请选择餐桌类型', trigger: 'change' }
  ]
}

// 计算属性：过滤后的餐桌列表
const filteredTables = computed(() => {
  return tables.value.filter(table => {
    const nameMatch = table.boardName.toLowerCase().includes(searchQuery.value.toLowerCase())
    const typeMatch = !filterType.value || table.boardType === filterType.value
    const statusMatch = !filterStatus.value || table.boardStatus === filterStatus.value
    const seatMatch = filterSeat.value === null || table.seat === filterSeat.value
    return nameMatch && typeMatch && statusMatch && seatMatch
  })
})

// 获取餐桌列表
const fetchTables = async () => {
  try {
    loading.value = true
    const result = await boardApi.getBoards([9, 10])
    if (result.code === 200 && result.data) {
      tables.value = result.data
    } else {
      ElMessage.error(result.message || '获取餐桌列表失败')
    }
  } catch (error) {
    ElMessage.error('获取餐桌列表失败')
    console.error(error)
  } finally {
    loading.value = false
  }
}

// 状态标签类型
const getStatusType = (status: string): string => {
  const types: Record<string, string> = {
    'UNINHABITED': 'info',    // 空闲
    'BOOKING': 'warning',     // 已预订
    'REPAST': 'success',      // 就餐中
    'DISABLE': 'danger'       // 停用
  }
  return types[status] || 'info'
}

// 获取状态标签文本
const getStatusText = (status: string): string => {
  const statusMap: Record<string, string> = {
    'UNINHABITED': '空闲',
    'BOOKING': '已预订',
    'REPAST': '就餐中',
    'DISABLE': '停用'
  }
  return statusMap[status] || '未知'
}

// 添加按钮处理
const handleAdd = () => {
  dialogType.value = 'add'
  resetForm()
  dialogVisible.value = true
}

// 编辑按钮处理
const handleEdit = (row: Table) => {
  dialogType.value = 'edit'
  form.value = { ...row }
  dialogVisible.value = true
}

// 删除按钮处理
const handleDelete = (row: Table) => {
  ElMessageBox.confirm('确定要删除该餐桌吗？', '提示', {
    confirmButtonText: '确定',
    cancelButtonText: '取消',
    type: 'warning'
  }).then(async () => {
    try {
      const result = await boardApi.deleteBoard(row.boardId)
      if (result.code === 200) {
        ElMessage.success('删除成功')
        await fetchTables()
      } else {
        ElMessage.error(result.message || '删除失败')
      }
    } catch (error) {
      ElMessage.error('删除失败')
      console.error(error)
    }
  })
}

// 重置搜索条件
const resetSearch = () => {
  searchQuery.value = ''
  filterType.value = ''
  filterStatus.value = ''
  filterSeat.value = null
}

// 表单提交处理
const handleSubmit = async () => {
  if (!formRef.value) return

  await formRef.value.validate(async (valid) => {
    if (valid) {
      try {
        let result

        if (dialogType.value === 'add') {
          // 添加时不需要boardId，由后端生成
          const { boardId, ...addData } = form.value

          // 根据餐桌类型设置区域ID
          if (addData.boardType === '普通') {
            addData.regionId = 9
          } else if (addData.boardType === '包厢') {
            addData.regionId = 10
          }

          result = await boardApi.addBoard(addData)
        } else {
          result = await boardApi.updateBoard(form.value)
        }

        if (result.code === 200) {
          ElMessage.success(dialogType.value === 'add' ? '添加成功' : '更新成功')
          dialogVisible.value = false
          await fetchTables()
        } else {
          ElMessage.error(result.message || (dialogType.value === 'add' ? '添加失败' : '更新失败'))
        }
      } catch (error) {
        ElMessage.error(dialogType.value === 'add' ? '添加失败' : '更新失败')
        console.error(error)
      }
    }
  })
}

// 重置表单
const resetForm = () => {
  if (formRef.value) {
    formRef.value.resetFields()
  }
  form.value = {
    boardId: 0,
    boardName: '',
    seat: 4,
    boardType: '普通',
    boardStatus: 'UNINHABITED',
    regionId: 9
  }
}

// 页面加载时获取数据
onMounted(async () => {
  await fetchTables()
})

// 监听form.boardType的变化
watch(() => form.value.boardType, (newType) => {
  if (dialogType.value === 'edit') {
    if (newType === '普通') {
      form.value.regionId = 9
    } else if (newType === '包厢') {
      form.value.regionId = 10
    }
  }
})
</script>

<style scoped>
.table-management-container {
  margin-left: 200px;
  margin-top: 45px;
  padding: 20px;
}

.card-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.title {
  font-size: 18px;
  font-weight: bold;
}

.search-area {
  margin-bottom: 20px;
}

.table-container {
  width: 100%;
  overflow-x: auto;
}

.table-list {
  width: 100%;
  border-collapse: collapse;
  margin-top: 20px;
  min-width: 800px;
}

.table-list th,
.table-list td {
  border: 1px solid #ddd;
  padding: 12px;
  text-align: center;
  color: #333;
  vertical-align: middle;
}

.table-list th {
  background-color: #f2f2f2;
  font-weight: bold;
  color: #333;
}

.table-list tbody tr:nth-child(even) {
  background-color: #f9f9f9;
}

.table-list tbody tr:hover {
  background-color: #f5f5f5;
}

.actions-column {
  white-space: nowrap;
  display: flex;
  justify-content: center;
  align-items: center;
  min-width: 180px;
  height: 60px;
}

.action-buttons {
  display: flex;
  gap: 8px;
  justify-content: center;
  width: 100%;
}

.action-buttons .el-button {
  display: flex;
  align-items: center;
  gap: 4px;
  margin: 0;
}

:deep(.el-select) {
  width: 100%;
}

.dialog-footer {
  display: flex;
  justify-content: flex-end;
  gap: 10px;
}

/* 响应式布局 */
@media screen and (max-width: 768px) {
  .table-management-container {
    margin-left: 0;
    width: 100%;
    padding: 10px;
  }

  .card-header {
    flex-direction: column;
    gap: 16px;
  }

  .title {
    width: 100%;
    text-align: center;
  }

  .search-area {
    .el-row {
      margin: 0 !important;
    }
    
    .el-col {
      padding: 0 !important;
      margin-bottom: 10px;
    }
  }

  .el-button {
    width: 100%;
    justify-content: center;
  }
}
</style> 